package com.rcl.mvvmdemo.player

import android.os.Looper
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Lifecycle.Event
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.rcl.mvvmdemo.SysApplication
import com.rcl.mvvmdemo.lifecycle.LifecycleState

/**
 * 数据容器
 * 可以监听数据的变化
 */
class DataListenerContainer<T> {

    private val blocks = arrayListOf<(T?) -> Unit>()
    private val viewLifecycleProviders = hashMapOf<(T?) -> Unit, Lifecycle>()

    var value: T? = null
        //当数据变化的时候，就通知更新
        set(value) {
            field = value
            //判断当前线程是不是主线程
            //如要是，则直接执行，否则切换到主线程再执行  确保线程UI 安全
            if (Looper.getMainLooper().thread === Thread.currentThread()) {
                //判断对应View的生命周期是什么
                blocks.forEach {
                    dispatchValue(it, value)
                }
            } else {
                SysApplication.handler.post {
                    blocks.forEach {
                        dispatchValue(it, value)
                    }
                }
            }
        }

    private fun dispatchValue(it: (T?) -> Unit, value: T?) {
        val lifecycle = viewLifecycleProviders[it]
        if (lifecycle != null && lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            Log.i("aaaaa", "更新UI...")
            it.invoke(value)
        } else {
            Log.i("aaaaa", "ui不可见，不进行更新...")
        }
    }

    /**
     * 有可能有多个View进行监听
     * 所有owner-block
     * 我们得管理起来
     */
    fun addListener(owner: LifecycleOwner, valueObserver: (T?) -> Unit) {
        val lifecycle: Lifecycle = owner.lifecycle
        viewLifecycleProviders[valueObserver] = lifecycle
        //当View destroy的时候，要从集合中删除
        val valueObserverWrapper = ValueObserverWrapper(valueObserver)
        lifecycle.addObserver(valueObserverWrapper)
        if (!blocks.contains(valueObserver)) {
            blocks.add(valueObserver)
        }
    }

    inner class ValueObserverWrapper(private val valueObserver: (T?) -> Unit) : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun removeValueObserver() {
            //Log.i("aaaaa", "removeValueObserver...")
            //当监听到当前的View，生命周期为destroy的时候，就把LifecycleProvider从集合中删除
            viewLifecycleProviders.remove(valueObserver)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop(owner: LifecycleOwner) {
            //Log.i("aaaaa", "onStop--> owner===>$owner")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
        fun onAny(owner: LifecycleOwner, event: Lifecycle.Event) {
            //Log.i("aaaaa", "owner===>$owner")
            //Log.i("aaaaa", "event===>$event")
        }
    }
}